package com.crm.service;

import com.crm.entity.Chance;
import com.crm.repository.ChanceRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("chanceService")
public class ChanceServiceImpl implements ChanceService {

    @Resource
    ChanceRepository chanceRepository;

    @Override
    public Page<Chance> findByChcCustNameLikeAndChcDescLike(String custName, String chcTitle, Pageable pageable) {
        Specification<Chance> specification = new Specification<Chance>() {
            @Override
            public Predicate toPredicate(Root<Chance> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (custName != null && !custName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("chcCustName"), "%" + custName + "%"));
                }
                if (chcTitle != null && !chcTitle.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("chcTitle"), "%" + chcTitle + "%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return chanceRepository.findAll(specification,pageable);
    }

    @Override
    public void del(Integer chcId) {
        chanceRepository.deleteById(chcId);
    }

    @Override
    public void save(Chance chance) {
        chanceRepository.save(chance);
    }

    @Override
    public Chance getChanceByChcId(Integer chcId) {
        return chanceRepository.findById(chcId).get();
    }
}
